<?php
namespace Common\Controller;

use Think\Controller;

abstract class BasicController extends Controller
{
	protected $pageSize = 10;
	
	protected $callback = null;
	
	protected function _initialize()
	{
		$this->callback = I('callback');
	}
	
	/**
	 * 路由心跳机制
	 * @param string $action 心跳方法名称
	 * @param string $continue 是否继续执行：默认不继续
	 */
	protected function methodRoute($action = true,$continue = false)
	{
		$method = strtolower(REQUEST_METHOD);
		
		$function = ucfirst(ACTION_NAME);
		
		$action = $action === true ? sprintf('%s%s%s',$method,$function,C('ACTION_SUFFIX')) : sprintf('%s%s%s',null,$action,C('ACTION_SUFFIX'));
		
		if( method_exists($this, $action) )
		{
			return $continue === false ? exit($this->$action()) : $this->$action();
		}
	}
	
	/**
	 * 文件、图片上传
	 */
	protected function saveFileAction()
	{
		$fileName = I('post.file');
		
		$config = C('file');
		
		$upload = new \Think\Upload($config['config'],$config['driver'],$config['driverConfig']);
		
		$info = $upload->upload(array($fileName=>$_FILES[$fileName]));
		
		if( $info === false )
		{
			return $this->error($upload->getError());
		}
		
		$info[$fileName]['url'] = sprintf('%s%s%s',$config['domain'],$info[$fileName]['savepath'],$info[$fileName]['savename']);
		
		return $this->success($info[$fileName]);
	}
	
	/**
	 * 编辑器内部上传
	 */
	protected function umeditorAction()
	{
		$fileName = 'upfile';
		
		$config = C('umeditor');
		
		$upload = new \Think\Upload($config['config'],$config['driver'],$config['driverConfig']);
		
		$info = $upload->upload(array($fileName=>$_FILES[$fileName]));
		
		$file = array(
				'state' => '初始化错误',
				'url' => null,
				'name' => null,
				'originalName' => null,
				'type' => null,
				'size' => null,
		);
		
		if( $info === false )
		{
			$file['state'] = $upload->getError();
		}
		else
		{
			$file['state'] = 'SUCCESS';
			$file['url'] = sprintf('%s%s%s',$config['domain'],$info[$fileName]['savepath'],$info[$fileName]['savename']);
			$file['name'] = $info[$fileName]['key'];
			$file['originalName'] = $info[$fileName]['name'];
			$file['type'] = $info[$fileName]['ext'];
			$file['size'] = $info[$fileName]['size'];
		}
		
		exit(json_encode($file));
	}
	
	public function debugAction()
	{
		dump(get_defined_constants(true));
	}
	
	public function sessionAction()
	{
		dump(session());
	}
}